package com.gton.handler;

import com.gton.io.Resp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @description: 全局异常处理：
 * @author: GuoTong
 * @createTime: 2022-11-27 11:17
 * @since JDK 1.8 OR 11
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // 全局异常拦截
    @ExceptionHandler
    public Resp handlerException(Exception e) {
        e.printStackTrace();
        log.error("服务执行异常---->{}", e.getMessage());
        return Resp.error(e.getMessage());
    }

    // 全局异常拦截
    @ExceptionHandler(value = ArithmeticException.class)
    public Resp handlerException(ArithmeticException e) {
        e.printStackTrace();
        log.error("Seata测试分布式事务回滚---->{}", e.getMessage());
        return Resp.error("Seata测试分布式事务回滚");
    }

    @ExceptionHandler(value = NotLoginException.class)
    public Resp handlerException(NotLoginException e,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
        log.error("没有登陆---->{}", e.getMessage());
        try {
            response.sendRedirect("/sso/login?back=" + request.getRequestURL());
        } catch (IOException ex) {
            log.error("转到认证中心失败---->{}", ex.getMessage());
        }
        return Resp.error(e.getMessage());
    }

    @ExceptionHandler(value = RedisLimitException.class)
    public Resp handlerException(RedisLimitException e) {
        log.error("限流触发---->{}", e.getMessage());
        return Resp.error(e.getMessage());
    }

    @ExceptionHandler(value = SQLException.class)
    public Resp msgMySQLExecuteError(Exception e) {
        e.printStackTrace();
        log.error("Mysql执行异常");
        String message = e.getMessage();
        return Resp.error(message);
    }


    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public Resp msgNotFind(Exception e) {
        e.printStackTrace();
        log.error("请求错误");
        String message = e.getMessage();
        return Resp.error("请求内容未传递" + message);
    }
}
